import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel
from PySide6.QtCore import QThread, Signal, QObject
import requests
 
class Worker(QObject):
    finished = Signal(str)  # 请求完成信号，传递结果
    error = Signal(str)    # 错误信号
 
    def run(self, url):
        try:
            response = requests.get(url, timeout=5)
            self.finished.emit(response.text)
        except Exception as e:
            self.error.emit(str(e))
 
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("非阻塞请求示例")
        self.setGeometry(100, 100, 400, 200)
        
        self.button = QPushButton("发起请求", self)
        self.button.setGeometry(150, 80, 100, 40)
        self.label = QLabel("等待请求...", self)
        self.label.setGeometry(150, 50, 200, 30)
        
        self.button.clicked.connect(self.start_request)
        
        # 创建线程和工作对象
        self.thread = QThread()
        self.worker = Worker()
        self.worker.moveToThread(self.thread)
        
        # 连接信号
        self.thread.started.connect(self.worker.run)
        self.worker.finished.connect(self.handle_results)
        self.worker.error.connect(self.handle_error)
        self.thread.finished.connect(self.thread.deleteLater)
 
    def start_request(self):
        url = "https://jsonplaceholder.typicode.com/posts/1"
        self.label.setText("请求中...")
        self.thread.start()  # 启动线程
        # 注意：不能直接传递参数到run，需通过事件循环
        # 实际使用中可通过信号/队列传递参数，此处简化示例
 
    def handle_results(self, result):
        self.label.setText(f"结果长度: {len(result)}")
        self.thread.quit()
 
    def handle_error(self, error):
        self.label.setText(f"错误: {error}")
        self.thread.quit()
 
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())